<?php
declare (strict_types=1);

namespace app\middleware;

use app\model\Users;
use Closure;
use think\Request;

class Auth
{
    /**
     * 处理请求
     *
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle($request, Closure $next)
    {
        $token = $request->header('Authorization');
        $request->isLogin = false;

        if (empty($token)) return $next($request);
        $token = str_replace('Bearer ', '', $token);

        if (empty($token)) return $next($request);
        if (\utils\Auth::verifyToken($token) === false) return $next($request);
        $user = \utils\Auth::verifyToken($token);
        if (empty($user)) return $next($request);
        $user = Users::where('id', $user->id)->find();
        $request->user = $user;
        $request->token = $token;
        $request->isLogin = true;
        return $next($request);
    }
}
